package ro.prjmanager.core.tag;

import net.sourceforge.stripes.tag.InputSelectTag;
import net.sourceforge.stripes.util.Log;

import javax.servlet.jsp.JspException;
import java.io.IOException;


public class SelectTag extends InputSelectTag {
    private static final Log log = Log.getInstance(SelectTag.class);
    private StringBuilder endTag;
    private boolean listStyle;
    private boolean ddStyle;


    public boolean isListStyle() {
        return listStyle;
    }

    public void setListStyle(boolean listStyle) {
        this.listStyle = listStyle;
    }

    public boolean isDdStyle() {
        return ddStyle;
    }

    public void setDdStyle(boolean ddStyle) {
        this.ddStyle = ddStyle;
    }



    @Override
    public int doStartInputTag() throws JspException {

         if(ddStyle&&!listStyle){
             setClass("multiselect");
         }
        super.doStartInputTag();
        return EVAL_BODY_INCLUDE;
    }

    private void doSelectList() {
        endTag=new StringBuilder();
        endTag.append("<script type=\"text/javascript\">\n");
        endTag.append("$(document).ready(function () {\n");
        endTag.append("$('select#").append(getId()).append("').selectList({\n");
        endTag.append("addAnimate: function (item, callback) {\n");
        endTag.append("$(item).slideDown(500, callback);\n");
        endTag.append("},\n");
        endTag.append("removeAnimate: function (item, callback) {\n");
        endTag.append("$(item).slideUp(500, callback);\n");
        endTag.append("}\n");
        endTag.append("})});\n");
        endTag.append("</script>");

    }

    private void doDragAndDropLists(){
        endTag=new StringBuilder();
        endTag.append(" <div id=\"switcher"+getId()+"\"></div>\n").append(
                "        <script type=\"text/javascript\">\n").append(
                "\t\t$(function(){\n").append(
                "\t\t\n").append(
                "\t\t\t$(\"#").append(getId()).append("\").multiselect();\n").append(
                "\t\t\t\n").append(
                "\t\t});\n").append(
                "\t</script>") ;

    }

    @Override
    public int doEndInputTag() throws JspException {
        super.doEndInputTag();
        if (listStyle)
            doSelectList();
        else if(ddStyle){

            doDragAndDropLists();
        }
        else endTag=new StringBuilder("");
            try {
                getPageContext().getOut().write(endTag.toString());
            } catch (IOException e) {
                JspException jspe = new JspException("IOException encountered while completing list-style tag");
                log.warn(jspe);
                throw jspe;
            }

        return EVAL_PAGE;
    }

}
